package com.zb.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.Tenant;
import com.zb.mapper.TenantMapper;
import com.zb.service.TenantService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import cn.hutool.core.util.RandomUtil;

@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Tenant> createTenants(int totalCount, int bigTenantPercentage) {
        if (totalCount <= 0) {
            return new ArrayList<>();
        }
        
        int bigTenantCount = (int) Math.round(totalCount * bigTenantPercentage / 100.0);
        int smallTenantCount = totalCount - bigTenantCount;
        
        List<Tenant> tenants = new ArrayList<>(totalCount);
        LocalDateTime now = LocalDateTime.now();
        
        // 创建大租户
        for (int i = 0; i < bigTenantCount; i++) {
            Tenant tenant = new Tenant();
            tenant.setName("Big Tenant " + RandomUtil.randomString(6));
            tenant.setType("BIG");
            // 大租户数据权重更高 (70-100)
            tenant.setDataWeight(RandomUtil.randomInt(70, 101));
            tenant.setCreateTime(now);
            tenant.setUpdateTime(now);
            tenant.setDeleted(0);
            tenants.add(tenant);
        }
        
        // 创建小租户
        for (int i = 0; i < smallTenantCount; i++) {
            Tenant tenant = new Tenant();
            tenant.setName("Small Tenant " + RandomUtil.randomString(6));
            tenant.setType("SMALL");
            // 小租户数据权重较低 (10-69)
            tenant.setDataWeight(RandomUtil.randomInt(10, 70));
            tenant.setCreateTime(now);
            tenant.setUpdateTime(now);
            tenant.setDeleted(0);
            tenants.add(tenant);
        }
        
        // 批量保存租户
        this.saveBatch(tenants);
        return tenants;
    }

    @Override
    public List<Tenant> getAllTenants() {
        return list();
    }
}
